package com.xiyuan.util;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;



/**
 * 上传文件实现类
 *
 * @author daodao
 *
 */
public class UploadManagerImpl  {

    private Log logger = LogFactory.getLog(UploadManagerImpl.class);

    private String rootPath = null;

   /* private long maxSize = 10000000000L;*/

    private static final String FILE_SEPARATOR = "/";

    /**
     * 初始化操作
     */
    public void init() {
        logger.info("init UploadService start.................");
        if (StringUtils.isBlank(rootPath)) {
            throw new NullPointerException("rootPath can't be null");
        }
        File f = new File(rootPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        rootPath = f.getPath();
        logger.info("init UploadService end...................");
    }

    public String uploadFile(MultipartFile multipartFile)
            throws UploadFileException {
        return saveFile(multipartFile, rootPath);
    }

    /**
     * 根据指定路径保存文件
     *
     * @param multipartFile
     * @param physiclePath
     * @return
     * @throws UploadFileException
     */
    private String saveFile(MultipartFile multipartFile, String physiclePath)
            throws UploadFileException {
        checkUploadFile(multipartFile);
        StringBuffer uploadFileName = genratorUploadFileName(multipartFile);
        uploadFileName.insert(0, FILE_SEPARATOR);
        try {
            File f = new File(physiclePath + uploadFileName.toString());
            if (!f.exists()) {
                f.mkdirs();
            }
            multipartFile.transferTo(f);
        } catch (IllegalStateException e) {
            logger.error("保存文件失败", e);
            throw new UploadFileException("保存文件失败");
        } catch (IOException e) {
            logger.error("保存文件失败", e);
            throw new UploadFileException("保存文件失败");
        }

        return uploadFileName.toString();
    }

    /**
     * 检查上传文件的大小和是否为空，可以进一步再这里增加文件上传的后缀判定
     *
     * @param multipartFile
     * @throws UploadFileException
     */
    private void checkUploadFile(MultipartFile multipartFile)
            throws UploadFileException {
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new UploadFileException("上传文件不能为空");
        }
      /*  if (multipartFile.getSize() > maxSize) {
            throw new UploadFileException("上传文件不能超过 " + maxSize/1024 + " k");
        }*/
    }
    
    /**
     * 检查上传文件是否为图片
     *
     * @param multipartFile
     * @throws UploadFileException
     */
    public void checkUploadImage(MultipartFile multipartFile)
            throws UploadFileException {       
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new UploadFileException("上传文件不能为空");
        }
        else{
            int length = multipartFile.getOriginalFilename().length();
            String fileType = multipartFile.getOriginalFilename().substring(length-3, length);
            if(!fileType.equalsIgnoreCase("jpg")&&!fileType.equalsIgnoreCase("gif")&&!fileType.equalsIgnoreCase("png")){
                throw new UploadFileException("文件类型只能是JPG, GIF, PNG ！");
            }
            else if(multipartFile.getSize()>10*1024*1024){
                throw new UploadFileException("上传文件不能超过 10MB");
            }
        }
    }

    /**
     * 生成上传文件的文件相对路径
     *
     * @param multipartFile
     * @return
     */
    private StringBuffer genratorUploadFileName(MultipartFile multipartFile) {
        StringBuffer uploadFileName = new StringBuffer(getYearMonWithoutDot(new Date()));
        uploadFileName.append(FILE_SEPARATOR);
        uploadFileName.append(UUID.randomUUID().toString());
        uploadFileName
                .append(getFileSuffix(multipartFile.getOriginalFilename()));
        return uploadFileName;
    }

    /**
     * 获取后缀
     *
     * @param fileName
     * @return
     */
    private String getFileSuffix(String fileName) {
        return StringUtils.substring(fileName, StringUtils.lastIndexOf(fileName,
                "."));
    }

    /**
     * 获取年月日
     * @param dt
     * @param mon
     * @return
     */
    private String getYearMonWithoutDot(Date dt) {
        if (dt == null) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        String year = String.valueOf(c.get(Calendar.YEAR));
        int month = c.get(Calendar.MONTH) + 1;
        String sMonth;
        if (month < 10) {
            sMonth = "0" + String.valueOf(month);
        } else {
            sMonth = String.valueOf(month);
        }
        return year + "" + sMonth;
    }

    public void setRootPath(String rootPath) {
        this.rootPath = rootPath;
    }

/*    public void setMaxSize(long maxSize) {
        this.maxSize = maxSize;
    }
*/
}
